
//Copyright 1997-2009 Syrinx Development, Inc.
//This file is part of the Syrinx Web Application Framework (SWAF).
// == BEGIN LICENSE ==
//
// Licensed under the terms of any of the following licenses at your
// choice:
//
//  - GNU General Public License Version 3 or later (the "GPL")
//    http://www.gnu.org/licenses/gpl.html
//
//  - GNU Lesser General Public License Version 3 or later (the "LGPL")
//    http://www.gnu.org/licenses/lgpl.html
//
//  - Mozilla Public License Version 1.1 or later (the "MPL")
//    http://www.mozilla.org/MPL/MPL-1.1.html
//
// == END LICENSE ==
using System;
using System.Net;
using System.Xml;
using System.Runtime.InteropServices;
using System.IO;
using System.Text;

namespace Ceridian
{
	class ResWebRequest : WebRequest
	{
		[DllImport("kernel32.dll")]
		public static extern int LoadLibrary(String name);
		[DllImport("kernel32.dll")]
		public static extern int FindResource(int module, String name, String type);
		[DllImport("kernel32.dll")]
		public static extern int LoadResource(int module, int resInfo);
		[DllImport("kernel32.dll")]
		public static extern string LockResource(int resInfo);
		[DllImport("kernel32.dll")]
		public static extern int SizeofResource(int module, int resInfo);
		[DllImport("kernel32.dll")]
		public static extern bool FreeLibrary(int module);

		private Uri m_uri;
		public ResWebRequest(Uri uri)
		{
			m_uri = uri;
		}

		private static string resURI = "res://";
		public override WebResponse GetResponse()
		{
			string fileName = m_uri.ToString();
			int pos = 0;
			if((pos = fileName.IndexOf(".dll")) != 0)
			{
				int resTypePos = pos + 5;
				string libraryName = fileName.Substring(resURI.Length,resTypePos - resURI.Length -1);
				int resNamePos = fileName.IndexOf("/",resTypePos) +1;
				string resTypeName = fileName.Substring(resTypePos, resNamePos - resTypePos -1);
				string resName = fileName.Substring(resNamePos);

				if(libraryName.Length != 0 && resName.Length != 0)
				{
					int libHandle = LoadLibrary(libraryName);
					if(libHandle == 0)
						throw new WebException("Unable to load library: " + libraryName + " From URI: " + fileName);
					try
					{
						int resInfoHandle = FindResource(libHandle,resName, resTypeName);
						if(resInfoHandle == 0)
							throw new WebException("Unable to find resource '" + resName +
									"' of type '" + resTypeName + "' in library: " + libraryName);
						int resHandle = LoadResource(libHandle,resInfoHandle);
						if(resHandle == 0)
							throw new WebException("Unable to LoadResource " + resName +
								" after finding it");
						//TODO: What if the script files are in unicode format (should that be allowed?)
						byte[] fileData = Encoding.ASCII.GetBytes(LockResource(resHandle).ToCharArray());
						if(fileData == null)
							throw new WebException("Unable to LockResource and retrieve data from " + resName);
						return new ResWebResponse(fileData, m_uri);
					}
					finally
					{
						FreeLibrary(libHandle);
					}

				}
			}
			return new ResWebResponse(null, m_uri);
		}

		public override Uri RequestUri { get {return m_uri;} }
		public override string Method { get{return "GET";} }
	}

	class RegCreator : IWebRequestCreate
	{
		public WebRequest Create(Uri uri)
		{
			return new ResWebRequest(uri);
		}
	}

	class ResWebResponse : WebResponse
	{
		private byte[] m_content;
		private Uri m_uri = null;
		public ResWebResponse(byte[] content, Uri uri)
		{
			m_content = content;
			m_uri = uri;
		}

		public override Stream GetResponseStream()
		{
			return new MemoryStream(m_content);
		}

		public override long ContentLength {get {return m_content.Length; } }
		public override string ContentType {get {return "text/text";} }
		public override Uri ResponseUri {get {return m_uri;} }
	}

	class App
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
			WebRequest.RegisterPrefix("res:", new RegCreator());

			WebRequest r = WebRequest.Create("http://cnn.com");
			Console.WriteLine("WebRequest.Method({0}) = {1}", r.RequestUri, r.Method);

			WebRequest r2 = WebRequest.Create(@"file://c:\data\healthhandlerapp\config\baseconfig-nodlls.xml");
			Console.WriteLine("WebRequest.Method({0}) = {1}", r2.RequestUri, r2.Method);

			WebRequest r3 = WebRequest.Create(@"res://c:\healthhandlercd\cut2\bin\hhconfig.dll/SWAFRES/\""CLIENTAPPCONFIG.XML""");
			Console.WriteLine("WebRequest.Method({0}) = {1}", r3.RequestUri, r3.Method);

			XmlDocument doc = new XmlDocument();
			doc.Load(@"res://c:\healthhandlercd\cut2\bin\hhconfig.dll/SWAFRES/\""CLIENTAPPCONFIG.XML""");
			Console.Write(doc.OuterXml);
		}

	}
}
